﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

using P2PLib.Common.DataModel;

namespace P2PLib.Common.Command
{
    public class CSConnectCommand:CSCommandBase
    {
        private ClientInfo clientInfo;

        public CSConnectCommand(ClientInfo c)
            : base(CSCommandType.Connect)
        {
            this.clientInfo = c;
        }

        public CSConnectCommand()
            :base(CSCommandType.Connect)
        {
            this.clientInfo = new ClientInfo("127.0.0.1", 0);
        }


        public override void ReadFromStream(Stream stream)
        {
                byte[] buffer=new byte[4];
                //read the client's port
                stream.Read(buffer,0,4);
                this.clientInfo.Port=BitConverter.ToInt32(buffer,0);

                //read the client's ip size;
                stream.Read(buffer,0,4);
                
            int ipSize = BitConverter.ToInt32(buffer,0);

            buffer = new byte[ipSize];
            //read the client's ip
            stream.Read(buffer, 0, ipSize);
            this.clientInfo.IP = IPAddress.Parse(Encoding.ASCII.GetString(buffer));

        }

        public override void WriteToStream(Stream stream)
        {
            //write the client's port to the stream
            byte[] buffer = BitConverter.GetBytes(this.clientInfo.Port);
            stream.Write(buffer, 0, 4);
            
            //write the client's ip size to the stream
            buffer =Encoding.ASCII.GetBytes( this.clientInfo.IP.ToString());
            stream.Write(BitConverter.GetBytes(buffer.Length), 0, 4);

            //write the client's ip to the stream
            stream.Write(buffer, 0, buffer.Length);
        }

        public ClientInfo Client
        {
            get { return clientInfo; }
            set { clientInfo = value; }
        }
    }
}
